package com.lineage.server.Instance;

import com.lineage.DatabaseFactory;
import com.lineage.server.datatables.map.MapLimitItemTable;
import com.lineage.server.utils.SQLUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MapLimitItemInstance {
  private static final Log log = LogFactory.getLog(MapLimitItemInstance.class);
  
  private static final Map<Integer, List<MapLimitItemTable>> mapsLimitItemList = new HashMap<>();
  
  private static MapLimitItemInstance instance;
  
  private MapLimitItemInstance() {
    load();
  }
  
  public void load() {
    Connection co = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
      co = DatabaseFactory.get().getConnection();
      ps = co.prepareStatement("SELECT * FROM `w_map_limit_item`");
      rs = ps.executeQuery();
      while (rs.next()) {
        MapLimitItemTable limitItemTable = new MapLimitItemTable();
        limitItemTable.setMapId(Integer.valueOf(rs.getInt("map_id")));
        limitItemTable.setItemId(Integer.valueOf(rs.getInt("item_id")));
        limitItemTable.setItemName(rs.getString("item_name"));
        putLimitItem(limitItemTable.getMapId(), limitItemTable);
      } 
    } catch (SQLException e) {
      log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(rs);
      SQLUtil.close(ps);
      SQLUtil.close(co);
    } 
    log.info("载入地图限制道具设定:" + mapsLimitItemList.size());
  }
  
  private void putLimitItem(Integer mapId, MapLimitItemTable limitItemTable) {
    List<MapLimitItemTable> mapLimitItemList = mapsLimitItemList.get(mapId);
    if (mapLimitItemList == null) {
      List<MapLimitItemTable> LimitItems = new ArrayList<>();
      LimitItems.add(limitItemTable);
      mapsLimitItemList.put(mapId, LimitItems);
    } else {
      mapLimitItemList.add(limitItemTable);
    } 
  }
  
  public static MapLimitItemInstance get() {
    if (instance == null)
      instance = new MapLimitItemInstance(); 
    return instance;
  }
  
  public Boolean checkLimitItemByMapId(Integer mapId, Integer itemId) {
    List<MapLimitItemTable> limitItems = getLimitItemsByMapId(mapId);
    for (MapLimitItemTable limitItem : limitItems) {
      if (limitItem.getItemId().equals(itemId))
        return Boolean.TRUE; 
    } 
    return Boolean.FALSE;
  }
  
  public List<MapLimitItemTable> getLimitItemsByMapId(Integer mapId) {
    return mapsLimitItemList.get(mapId);
  }
}
